package com.phonetools.commonutils.file

import android.content.Context
import android.net.Uri
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

private val LINE_SEP = System.getProperty("line.separator")

/**
 * 读取文件到字符串中
 *
 * @param uri
 * @param charsetName 编码格式
 * @return 字符串
 */
fun readUri2String(context: Context, uri: Uri, charsetName: String? = null): String? {
    var reader: BufferedReader? = null
    try {
        val inputStream = context.contentResolver.openInputStream(uri) ?: return null
        val sb = StringBuilder()
        reader = if (charsetName.isNullOrEmpty()) {
            BufferedReader(InputStreamReader(inputStream))
        } else {
            BufferedReader(InputStreamReader(inputStream, charsetName))
        }
        var line: String? = reader.readLine()
        if (!line.isNullOrEmpty()) {
            sb.append(line)
        }
        do {
            line = reader.readLine()
            if (!line.isNullOrEmpty()) {
                sb.append(LINE_SEP).append(line)
            }
        } while (!line.isNullOrEmpty())
        return sb.toString()
    } catch (e: IOException) {
        e.printStackTrace()
        return null
    } finally {
        closeIO(reader)
    }
}

/**
 * 读取Uri文件到ByteArray中
 *
 * @param uri
 * @return ByteArray
 */
fun readUri2ByteArray(context: Context, uri: Uri): ByteArray? {
    return try {
        context.contentResolver.openInputStream(uri)?.readBytes()
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}